package xiaohongshu

import (
	"answer5/adb"
	log2 "answer5/log"
	"answer5/unti"
	"encoding/json"
	"encoding/xml"
	"errors"
	"log"
	"strconv"
	"strings"
	"time"
)

var(
	question = unti.Question{}
	isStart *bool
	isNewQuestion bool
)

func Start(start *bool){
	isStart = start

	for{
		if !*isStart{
			break
		}
		//t1 := time.Now()
		CreateQuestion(adb.GetHierarchy())
		//elapsed := time.Since(t1)
		//fmt.Println("App elapsed: ", elapsed)

		time.Sleep(1*time.Second)
	}

	//for i:=1;i<=3 ;i++  {
	//	if !*isStart{
	//		break
	//	}
	//	f, err := os.OpenFile("G:\\hierarchy\\question"+strconv.Itoa(i)+".txt", os.O_RDONLY,0600)
	//	if err != nil{
	//		f.Close()
	//		go log2.LogPrint(err.Error())
	//	}
	//	body,err:=ioutil.ReadAll(f)
	//
	//
	//	CreateQuestion(&body)
	//	time.Sleep(3*time.Second)
	//}

}
func Stop(start *bool){
	isStart = start
	NewQuestion(0,&question.Title)
}

func CreateQuestion(body *[]byte )  {
	if body == nil{
		unti.SendErr(errors.New("CreateQuestion"),"GetHierarchy断开")
		*isStart = false
		return
	}
	var jsonObj HierarchyRaw
	err := json.Unmarshal(*body, &jsonObj)
	if err != nil{
		log.Println("CreateQuestion:",err)
		go log2.LogPrint(err.Error())
	}
	//fmt.Println(jsonObj)
	xmlData := HierarchyXml{}
	err = xml.Unmarshal([]byte(jsonObj.Result), &xmlData)
	if err != nil{
		log.Println("CreateQuestion:",err)
		go log2.LogPrint(err.Error())
	}
	GetQuestionNode(&xmlData.Nodes)
	//fmt.Println(question)
	if isNewQuestion{
		go unti.NewQuestion(&question)
	}
}

func GetQuestionNode(nodes *[]Node){
	for _,node := range *nodes{
		switch node.ResourceId {
		case "com.xingin.xhs:id/eeq":
			spIndex := strings.Index(node.Text," ")
			rounds := strings.Split(node.Text[0:spIndex],"/")
			round,_ := strconv.Atoi(rounds[0])
			title := node.Text[spIndex+1:]

			//sp := strings.Split(node.Text," ")
			//question.Title = sp[1]
			//rounds := strings.Split(sp[0],"/")
			//round,_ := strconv.Atoi(rounds[0])
			//question.Round = int32(round)
			if int32(round) > question.Round{
				isNewQuestion = true
				NewQuestion(int32(round),&title)
			}else{
				isNewQuestion = false
			}
		case "com.xingin.xhs:id/e8h":
			question.Options = append(question.Options, unti.Option{Text:node.Text})
		}
		//fmt.Println(node.ResourceId, node.Text)
		if node.Nodes != nil{
			GetQuestionNode(&node.Nodes)
		}
	}
}

func Test(){

}

func NewQuestion(index int32,title *string){
	question.Title=*title
	question.Options=[]unti.Option{}
	question.Round = index
	question.Result=""
}

type HierarchyRaw struct {
	Result string `json:"result"`
}

type HierarchyXml struct {
	XMLName xml.Name `xml:"hierarchy"`
	Rotation string `xml:"rotation,attr"`
	Nodes []Node `xml:"node"`
}

type Node struct {
	Text string `xml:"text,attr"`
	ResourceId string `xml:"resource-id,attr"`
	Nodes []Node `xml:"node"`
}